<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:param="{row}">
      <json_param :config="param_config" v-model:value="param_row"></json_param>
    </template>
    <template v-slot:content="{row}">
      <div style="font-family: inherit;margin:0;display:inline;white-space: pre-wrap;text-align: left;width: 100%;">{{vue_template(row.value, decode_json(param_row))}}</div>
    </template>
  </forms>
</template>

<script>
import {ajax} from "@/js/api_tool.js";
import s94Mjs from "s94-js";
import {iframe} from "@/js/tool.js";
import {vue_template} from "@/js/dom_tool.js";
import json_param from "@/components/auto_import/UnifyParam/json_param.vue";

export default {
  components: {json_param},
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    if (!id) iframe.remove('send');
    let forms_config = {
      user_id: {label:'指定用户',name:'user_id',type:'list_id',config:'/user/index',tips:'指定接收消息的用户'},
      param: {label:'发送参数',name:'param',type:'param',tips:'',value:'{}'},
      content: {label:'消息预览',name:'content',type:'content',tips:'',value:''}
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      param_config: {},
      param_row: '{}',
    }
  },
  methods: {
    vue_template: vue_template,
    onsubmit(formData){
      let url = `/admin/message_template/send?id=`+this.id;
      let data = {user_id: formData.get('user_id')}
      for (const k in this.param_config) {
        let row = this.param_config[k];
        if (!row.value) return this.$message.error(row.label+' 参数不能为空');
        data[k] = row.value;
      }
      ajax({url:url, method:'POST', data:data}, (res)=>{
        if (this.__iframe){
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    decode_json(json){
      return JSON.parse(json);
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/message_template/info?id='+this.id, cache:true}, (res)=>{
        s94Mjs.each(JSON.parse(res.data['param']), function (v,k){
          app.param_config[k] = {label:v,name:k,type:'text_one'};
        })
        this.$refs['forms'].init(res.data);
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('message_template/send');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
  }
}
</script>
